package com.cy;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class GatewayConfig {
    public GatewayConfig() {
        //限流异常处理策略
        GatewayCallbackManager.setBlockHandler(new BlockRequestHandler() {
            //当我们请求的url被限流了可以直接执行此方法，在此方法中我们进行限流响应数据的设计
            //此方法的返回值可以响应到客户端
            @Override
            public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {
                Map<String, Object> map = new HashMap<>();
                map.put("state", 0);
                map.put("message", "请求次数太多了，请稍后再试");
                String jsonStr = JSON.toJSONString(map);//将map对象转换为json
                return ServerResponse.ok().body(Mono.just(jsonStr), String.class);
             /*   try {
                    String jsonStr = new ObjectMapper().writeValueAsString(map);
                    //返回值，如何构建需要基于方法返回值类型，进行源码参考
                    return ServerResponse.ok().body(Mono.just(jsonStr), String.class);
                }catch (Exception e){e.printStackTrace();
                    e.printStackTrace();
                    throw new RuntimeException(e.getMessage());
                }*/
            }
        });
    }
}
